﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gedea.Model;
using System.Data;
using System.Data.SqlClient;
using Gedea.Model.Entities;
using Gedea.Core.Manager;
using Gedea.Core.Manager.DataAccess;

namespace Gedea.Core.Repositories
{
    public class ConfigurationRepository
    {
        #region Public Methods

        public void CreateDatabase()
        {
            string str;
            try
            {
                using (SqlConnection myConn = new SqlConnection(DataConnection.GetMasterConnection()))
                {
                    str = string.Format("CREATE DATABASE {0}", DataConnection.DBName);
                    SqlCommand myCommand = new SqlCommand(str, myConn);

                    myConn.Open();
                    myCommand.ExecuteNonQuery();
                    myConn.Close();
                }
            }
            catch (System.Exception ex)
            {

            }
        }

        public void CreateTables()
        {
            new DataCreate().CreateTable<User>();

            new DataCreate().CreateTable<Area>();
            new DataCreate().AddConstraint<Area, User>(true);

            new DataCreate().CreateTable<Customer>();
            new DataCreate().AddConstraint<Customer, Area>(true);
            new DataCreate().AddConstraint<Customer, User>(false);
        }

        public bool IsDataBaseCreated()
        {
            bool res = true;
            string str;
            try
            {
                using (SqlConnection myConn = new SqlConnection(DataConnection.GetMasterConnection()))
                {
                    str = string.Format("SELECT NAME FROM sysdatabases WHERE name = N'{0}'", DataConnection.DBName);
                    SqlCommand myCommand = new SqlCommand(str, myConn);

                    myConn.Open();

                    res = myCommand.ExecuteReader().HasRows;

                    myConn.Close();
                }
            }
            catch (System.Exception ex)
            {

            }
            return res;
        }
        #endregion
    }
}
